﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace DetectorReader
{
    class WebSocketDataSender
    {
        public delegate void EventMsg(string msg);
        private WebSocketServer ws;
        EventMsg eventMsg;
        public WebSocketDataSender(int port, EventMsg eventMsg)
        {
            ws = new WebSocketServer(port);
            ws.AddWebSocketService("/", ()=>new Laputa(eventMsg));
            ws.Start();
            if (!ws.IsListening)
            {
                throw new Exception("websocket服务启动失败");
            }
        }

        Laputa InitWebSocket(EventMsg eventMsg)
        {
            return new Laputa(eventMsg);
        }

        internal void Send(string data)
        {
            ws?.WebSocketServices.BroadcastAsync(data, null);
        }

        internal void Close()
        {
            ws.Stop();
            ws = null;
        }

        private class Laputa : WebSocketBehavior
        {
            EventMsg eventMsg;
            public Laputa(EventMsg em)
            {
                eventMsg = em;
            }
            protected override void OnOpen()
            {
                eventMsg("客户端连接成功");
            }

            protected override void OnClose(CloseEventArgs e)
            {
                eventMsg("客户端关闭了连接");
            }
        }
    }

    
}
